import { bootstrapControllers } from 'koa-ts-controllers';
import Koa = require('koa');
import KoaBody from 'koa-body';
import KoaRouter = require('koa-router');

import path = require('path');
import configs from './config';
import { Context } from 'koa';
import mystatus from './define/status';


const app = new Koa();
const router = new KoaRouter();

(async () => {
    await bootstrapControllers(app, {
        router: router,
        basePath: '/api',
        versions: [1],
        controllers: [
            __dirname + '/controllers/**/*'
        ],
        errorHandler: async(err: any, ctx: Context) => {
            let status = mystatus.httpStatus.serverError;
            let body: any = {
                "statusCode": mystatus.httpStatus.serverError,
                "error": "Internal Server error",
                "message": "An internal server error occurred"
            };

            if(err.output) {
                status = err.output.statusCode;
                body = {...err.output.payload};
                if(err.data) {
                    body.errorDetails = err.data;
                }
            }

            ctx.staturs = status;
            ctx.body = body;
        }
    });

    app.use(KoaBody({
        multipart: true
    }));

    app.use(router.routes());
    app.listen(configs.server.port, configs.server.host, () => {
        console.log(`成功启动服务，url: http://${configs.server.host}:${configs.server.port}`);
    });

})();



